package com.prp.gwt.client.widgets.user.php;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Widget;
import com.prp.gwt.client.user.friend.FriendListener;
import com.prp.gwt.client.user.php.PHPHistoryHandler;
import com.prp.gwt.client.user.profile.ProfileHistoryHandler;
import com.prp.gwt.client.vo.User;
import com.prp.gwt.client.vo.UserStateList;

public class UserInfoPanel extends Composite {

	interface Binder extends UiBinder<Widget, UserInfoPanel> {
	}

	private static final Binder binder = GWT.create(Binder.class);
	public static UserInfoPanel instance;
	private User user;
	
	@UiField
	Image portrait;
	@UiField
	HTML regName;
	@UiField
	HTML realName;
	@UiField
	HTML state;
	@UiField
	HTML edit;
	@UiField
	HTML addFriend;
	@UiField
	HTML introduction;
	@UiField
	HTML blog;
	@UiField
	HTML address;
	
	public static UserInfoPanel getInstance() {
		return instance;
	}

	public UserInfoPanel() {
		instance = this;
		initWidget(binder.createAndBindUi(this));
		edit.setHTML("<a>编辑资料</a>");
		edit.addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				History.newItem(ProfileHistoryHandler.INIT_VALUE);
			}
		});
		addFriend.setHTML("<a>加为好友</a>");
		addFriend.addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				FriendListener.getInstance().invite(user);
			}
		});
	}

	public void init() {
		portrait.setUrl("");
		regName.setHTML("&nbsp");
		realName.setHTML("&nbsp");
		state.setHTML("&nbsp");
		introduction.setHTML("&nbsp");
		blog.setHTML("&nbsp");
		address.setHTML("&nbsp");
		edit.setVisible(false);
		addFriend.setVisible(false);
	}

	public void load(User user) {
		this.user = user;
		portrait.setUrl(user.getPortrait());
		if (user.getUsername() != null) {
			regName.setText(user.getUsername());
		}
		if (user.getRealname() != null) {
			realName.setText(user.getRealname());
		}
		if(user.getIntroduction() != null){
			introduction.setText(user.getIntroduction());
		}
		if(user.getBlog() != null){
			blog.setText(user.getBlog());
		}
		if(user.getAddress() != null){
			address.setText(user.getAddress());
		}
		if (History.getToken().equals(PHPHistoryHandler.INIT_VALUE))
			edit.setVisible(true);
		else if (!user.isNeighbour())
			addFriend.setVisible(true);
	}

	public void load(UserStateList latestState) {
		load(latestState.getOwner());
		if (latestState.get(0).getState() != null) {
			state.setText(latestState.get(0).getState());
		}
	}

}
